import flash.external.ExternalInterface;
dynamic class JSSynchronize{
	public static var M_SYNC:String="onSync";
	private var $root:MovieClip;
	private var _say:Say;
	private var $interIdName:String="___interId";
	private var startSysTime:Date;
	
	public static var _msg:Function;
	public function JSSynchronize(root:MovieClip){
		this._say=new Say("JSS");
		this[Say.M_SAY]=this.SayFun;
		this._say.addListener(this);
		if(root==undefined){
			this._say.esay("root mc can't be null!");
			return;
		}
		this.$root=root;
		this.$interIdName+=(new Date()).getTime().toString();
		root[this.$interIdName]=-1;
		initBroadcastor();
	}
	private function initBroadcastor(){
		AsBroadcaster.initialize(this);
	}
	
	public function startSyn(funname:String,timeOut:Number,sysRate:Number){
		if(funname==undefined){
			this._say.esay("Need Sysn-JS function name.");
			return;
		}
		if(timeOut==undefined|| timeOut<0 || timeOut==null){
			timeOut=9999999999999;
		}
		if(sysRate==undefined){
			sysRate=1000;
		}
		if(this.$root[this.$interIdName]<0){
			this.startSysTime=new Date();
			this.$root[this.$interIdName]=setInterval(this.interFun,sysRate,this,funname,timeOut);
		}else{
			this._say.msay("JSSynchronize is working.");
		}
	}
	
	private function interFun(jss:JSSynchronize,fn:String,timeout:Number,sysrate:Number){
		//trace("jjjjjjjjjjjjjjjjjj = "+jss.$root.toString());
		if(jss.$root==null || jss.$root==undefined ||jss.$root.toString()==undefined ){
			jss.stopSyn();
			return;
		}
		jss._say.msay("call for synchronize with JS ("+fn+")");
		var backObj:Object=ExternalInterface.call(fn);
		if(backObj.toString()=="true"){
			jss.broadcastMessage(JSSynchronize.M_SYNC,true);
			jss.stopSyn();
		}else{
			var ms:Number=(new Date()).getTime()-jss.startSysTime.getTime();
			if(timeout<ms){
				jss.broadcastMessage(JSSynchronize.M_SYNC,false);
				jss._say.msay("call ("+fn+") Time Out["+timeout+"]");
				jss.stopSyn();
			}
		}
	}
	
	public function stopSyn(){
		if(this.$root[this.$interIdName]>=0){
			clearInterval(this.$root[this.$interIdName]);
			this.$root[this.$interIdName]=-1;
		}else{
			this._say.msay("JSSynchronize isn't working.");
		}
	}
	
	private function SayFun(o:Object){
		_msg(o);
		trace(o);
	}
}